package com.easytopit.demo.spring.mvc.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传
 * 
 * @author panqingshan
 *
 */
@Controller
public class UploadController {

	@RequestMapping(value = "/upload.htm")
	public String uploadPage(HttpServletRequest request, HttpServletResponse response) {
		return "upload/file";
	}

//	@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
//	public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, ModelMap modelMap) {
//		// 无上传文件
//		if (file.isEmpty()) {
//			// 重定向
//			return "redirect:/upload.htm"; // forward:/upload.htm
//		}
//		// 设置存放的文件名以及目录
//		int lastIndexOf = file.getOriginalFilename().lastIndexOf(".");
//		String oriFileNameSuffix = lastIndexOf != -1 ? file.getOriginalFilename().substring(lastIndexOf): "";
//		String destFileName = UUID.randomUUID() + oriFileNameSuffix;
//		String destFilePath = request.getSession().getServletContext().getRealPath("/") + "/upload/";
//		File destFile = new File(destFilePath, destFileName);
//		if(!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs();
//		// 转存到服务器本地目录
//		try {
//			file.transferTo(destFile);
//		} catch (IllegalStateException | IOException e) {
//			e.printStackTrace();
//			// 重定向
//			return "redirect:/upload.htm"; // forward:/upload.htm
//		}
//		modelMap.put("name", destFileName);
//		return "upload/result";
//	}
	
//	<!-- @11 使用Servlet3.0 文件文件功能 -->
	@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
	public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, ModelMap modelMap) {
		// 无上传文件
		if (file.isEmpty()) {
			// 重定向
			return "redirect:/upload.htm"; // forward:/upload.htm
		}
		// 设置存放的文件名以及目录
		int lastIndexOf = file.getOriginalFilename().lastIndexOf(".");
		String oriFileNameSuffix = lastIndexOf != -1 ? file.getOriginalFilename().substring(lastIndexOf): "";
		String destFileName = UUID.randomUUID() + oriFileNameSuffix;
		String destFilePath = request.getServletContext().getRealPath("/") + "/upload/";
		File destFile = new File(destFilePath, destFileName);
		if(!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs();
		// 转存到服务器本地目录
		try {
			file.transferTo(destFile);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			// 重定向
			return "redirect:/upload.htm"; // forward:/upload.htm
		}
		modelMap.put("name", destFileName);
		return "upload/result";
	}
	

}
